#include"DemoQueryAABB.h"
#include"LSYEasyBody.h"
#include"LSYEasyWorld.h"
#include"GLES-Render.h"
#include"Tool.h"
#include<string>

USING_NS_CC;

bool DemoQueryAABB::init()
{
	if (!AbstractLayer::init(b2Vec2(0, -10)))
	{
		return false;
	}
	return true;
}

void DemoQueryAABB::box2DAppReady()
{
	auto size = Director::getInstance()->getWinSize();
	LSYEasyBody::createRectangle(b2Vec2(0, 0), size.width, size.height);
	
	createBodies();
}

void DemoQueryAABB::createBodies()
{
	LSYEasyBody::createBox(b2Vec2(205, 335), b2Vec2(30, 30));
	LSYEasyBody::createBox(b2Vec2(295, 335), b2Vec2(30, 30));
	LSYEasyBody::createBox(b2Vec2(250, 305), b2Vec2(120, 30));
	LSYEasyBody::createBox(b2Vec2(235, 245), b2Vec2(90, 30));
	
	b2Body* b = LSYEasyBody::createBox(b2Vec2(250, 275), b2Vec2(60, 30));
	b->SetUserData(&unRemoveable);
	b = LSYEasyBody::createBox(b2Vec2(250, 200), b2Vec2(120, 30));
	b->SetUserData(&unRemoveable);
}

void DemoQueryAABB::drawAABB(b2Color color)
{
	pDebug->DrawAABB(&ab, color);
}

bool DemoQueryAABB::ReportFixture(b2Fixture * fixture)
{
	b2Body* body = fixture->GetBody();
	b2Shape* shape = fixture->GetShape();

	if (shape->TestPoint(body->GetTransform(), mousePoint))
	{
		if (body->GetUserData()==nullptr)
		{
			pWorld->DestroyBody(body);
			return false;
		}
	}
	return true;
}

void DemoQueryAABB::onTouchEnded(cocos2d::Touch * touch, cocos2d::Event * unused_event)
{
	mousePoint.Set(touch->getLocation().x*PTM_RADIO, touch->getLocation().y*PTM_RADIO);
	ab.lowerBound.Set(mousePoint.x - abSize, mousePoint.y - abSize);
	ab.upperBound.Set(mousePoint.x + abSize, mousePoint.y + abSize);
	pWorld->QueryAABB(this, ab);
}

void DemoQueryAABB::draw(cocos2d::Renderer * renderer, const cocos2d::Mat4 & transform, uint32_t flags)
{
	AbstractLayer::draw(renderer, transform, flags);
	drawAABB(color);
}
